using Godot;
using System;
using System.Linq;

[Tool] // 编辑器实时预览
public partial class LaserDoor : StaticBody2D
{
    [ExportGroup("配置")]
    [Export] public string[] DoorTags; // 标签，如 ["lv1_door"]
    [Export] public Vector2 DoorSize = new Vector2(32, 128);
    [Export] public Color LaserColor = new Color(0, 1, 1);

    // 内部组件
    private CollisionShape2D _collisionShape;
    private ColorRect _visualRect; // 用 ColorRect 来显示激光
    private ShaderMaterial _material;

    public override void _Ready()
    {
        _collisionShape = GetNode<CollisionShape2D>("CollisionShape2D");
        _visualRect = GetNode<ColorRect>("ColorRect");

        UpdateDoorSize();

        if (Engine.IsEditorHint()) return;

        // --- 游戏运行逻辑 ---

        // 复制材质，防止多扇门联动
        if (_visualRect.Material is ShaderMaterial sm)
        {
            _material = (ShaderMaterial)sm.Duplicate();
            _visualRect.Material = _material;
            _material.SetShaderParameter("color", LaserColor);
        }

        // 连接信号
        GameState.Instance.Connect(GameState.SignalName.DoorStateChanged, Callable.From<string, bool>(OnDoorStateChanged));
    }

    public override void _Process(double delta)
    {
        if (Engine.IsEditorHint())
        {
            UpdateDoorSize();
        }
    }

    private void UpdateDoorSize()
    {
        if (_collisionShape == null || _visualRect == null) return;

        // 1. 设置碰撞体 (RectangleShape2D)
        if (_collisionShape.Shape is RectangleShape2D rectShape)
        {
            rectShape.Size = DoorSize;
        }

        // 2. 设置视觉矩形
        _visualRect.Size = DoorSize;
        // ColorRect 默认原点在左上角，StaticBody2D 原点在中心
        // 所以要偏移一半位置，让它居中
        _visualRect.Position = -DoorSize / 2;
    }

    private void OnDoorStateChanged(string tag, bool isOpen)
    {
        if (DoorTags.Contains(tag))
        {
            SetDoorState(isOpen);
        }
    }

    private void SetDoorState(bool isOpen)
    {
        Tween tween = CreateTween();

        if (isOpen)
        {
            // 开门：碰撞体禁用
            _collisionShape.SetDeferred("disabled", true);

            // Shader 动画：open_progress 从 0 变 1 (中间向两边消失)
            tween.TweenMethod(Callable.From<float>(SetShaderOpen), 0.0f, 1.0f, 0.5f)
                .SetTrans(Tween.TransitionType.Cubic).SetEase(Tween.EaseType.Out);
        }
        else
        {
            // 关门：Shader 动画：open_progress 从 1 变 0
            tween.TweenMethod(Callable.From<float>(SetShaderOpen), 1.0f, 0.0f, 0.5f)
                .SetTrans(Tween.TransitionType.Cubic).SetEase(Tween.EaseType.Out);

            // 动画结束恢复碰撞
            tween.TweenCallback(Callable.From(() => _collisionShape.Disabled = false));
        }
    }

    private void SetShaderOpen(float value)
    {
        if (_material != null)
        {
            _material.SetShaderParameter("open_progress", value);
        }
    }
}